package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUserMachine;
import org.dromara.system.domain.bo.*;
import org.dromara.system.domain.vo.SummaryTradingPointsVo;
import org.dromara.system.domain.vo.SysUserMachineVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.CreditCardRewardRecordsMapper;
import org.dromara.system.mapper.SysUserMachineMapper;
import org.dromara.system.mapper.TradingRecordsMapper;
import org.dromara.system.service.ISysUserMachineService;
import org.dromara.system.service.ISysUserService;
import org.dromara.system.service.impl.permission.PermissionBaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 机具信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-08
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserMachineServiceImpl extends ServiceImpl<SysUserMachineMapper, SysUserMachine> implements
    ISysUserMachineService {

    private final PermissionBaseService permissionBaseService;
    private final ISysUserService userService;
    private final TradingRecordsMapper tradingRecordsMapper;
    private final CreditCardRewardRecordsMapper creditCardRewardRecordsMapper;

    /**
     * 查询机具信息
     *
     * @param id 主键
     * @return 机具信息
     */
    @Override
    public SysUserMachineVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询机具信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 机具信息分页列表
     */
    @Override
    public TableDataInfo<SysUserMachineVo> queryPageList(SysUserMachineBo bo, PageQuery pageQuery) {
//        permissionBaseService.aloneAssignPermission(bo);
        IPage<SysUserMachineVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SysUserMachineVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);

    }

    /**
     * 查询符合条件的机具信息列表
     *
     * @param bo 查询条件
     * @return 机具信息列表
     */
    @Override
    public List<SysUserMachineVo> queryList(SysUserMachineBo bo) {
        LambdaQueryWrapper<SysUserMachine> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserMachine> buildQueryWrapper(SysUserMachineBo bo) {
        LambdaQueryWrapper<SysUserMachine> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysUserMachine::getId);
        lqw.eq(bo.getUserId() != null, SysUserMachine::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getSn()), SysUserMachine::getSn, bo.getSn());
        lqw.eq(bo.getDealSum() != null, SysUserMachine::getDealSum, bo.getDealSum());
        return lqw;
    }

    /**
     * 新增机具信息
     *
     * @param bo 机具信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SysUserMachineBo bo) {
        SysUserMachine add = MapstructUtils.convert(bo, SysUserMachine.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改机具信息
     *
     * @param bo 机具信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysUserMachineBo bo) {
        SysUserMachine update = MapstructUtils.convert(bo, SysUserMachine.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserMachine entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除机具信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            List<SysUserMachine> sysUserMachines = lambdaQuery().in(SysUserMachine::getId, ids).list();
            List<SysUserMachine> list = sysUserMachines.stream().filter(t -> ObjectUtil.isNotNull(t.getBindUserId())).toList();
            BusinessException.isTrue(CollUtil.isNotEmpty(list), "已被商户绑定的机器禁止删除");
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveMachine(MachinePutBo machinePutBo, String sn) {
        SysUserMachine sysUserMachine = lambdaQuery().eq(SysUserMachine::getSn, sn).one();
        BusinessException.notNull(sysUserMachine, "该sn已存在！");
        SysUserMachineBo sysUserMachineBo = new SysUserMachineBo();
        sysUserMachineBo.setMachinePolicyId(machinePutBo.getMachinePolicyId());
        sysUserMachineBo.setBrandId(machinePutBo.getBrandId());
        sysUserMachineBo.setLineId(machinePutBo.getLineId());
        sysUserMachineBo.setMachineModelId(machinePutBo.getMachineModelId());
        sysUserMachineBo.setUserId(machinePutBo.getUserId());
        sysUserMachineBo.setSn(sn);
        insertByBo(sysUserMachineBo);
        return Boolean.TRUE;
    }

    @Override
    public Boolean bindMachine(BindMachineBo bindMachineBo) {
        if (ObjectUtil.isNull(bindMachineBo.getUserId())) {
            bindMachineBo.setUserId(LoginHelper.getUserId());
        }
        SysUserVo sysUserVo = userService.selectUserById(bindMachineBo.getUserId());
        SysUserMachine sysUserMachine = lambdaQuery().eq(SysUserMachine::getSn, bindMachineBo.getSn()).one();
        BusinessException.isNull(sysUserMachine, "该sn不存在！");
        BusinessException.isTrue(ObjectUtil.notEqual(sysUserVo.getOneId(), sysUserMachine.getUserId()), "sn不在当前一级名下！");
        BusinessException.notNull(sysUserMachine.getBindUserId(), "该sn已经被绑定！");
        lambdaUpdate().set(SysUserMachine::getBindUserId, bindMachineBo.getUserId())
            .set(SysUserMachine::getBindTime, DateUtil.date())
            .eq(SysUserMachine::getId, sysUserMachine.getId())
            .update();
        return Boolean.TRUE;
    }

    @Override
    public Boolean unBindMachine(BindMachineBo bindMachineBo) {
        Long userId = LoginHelper.getUserId();
        SysUserMachine sysUserMachine = lambdaQuery().eq(SysUserMachine::getSn, bindMachineBo.getSn()).one();
        BusinessException.isNull(sysUserMachine, "该sn不存在！");
        Long bindUserId = sysUserMachine.getBindUserId();
        BusinessException.isTrue(ObjectUtil.notEqual(bindUserId, userId), "该机器未绑定在自己名下！");
        lambdaUpdate().set(SysUserMachine::getBindUserId, null)
            .set(SysUserMachine::getBindTime, null)
            .eq(SysUserMachine::getId, sysUserMachine.getId())
            .update();
        return Boolean.TRUE;
    }

    @Override
    public Boolean backendUnBindMachine(BackendUnBindMachineBo bo) {
        Long terminalId = bo.getTerminalId();
        SysUserMachine sysUserMachine = lambdaQuery().eq(SysUserMachine::getId, terminalId).one();
        BusinessException.isNull(sysUserMachine, "该sn不存在！");
        lambdaUpdate().set(SysUserMachine::getBindUserId, null)
            .set(SysUserMachine::getBindTime, null)
            .eq(SysUserMachine::getId, sysUserMachine.getId())
            .update();
        return Boolean.TRUE;
    }

    @Override
    public TableDataInfo<SysUserMachineVo> queryBindMachine(QueryBindMachineBo queryBindMachineBo, PageQuery pageQuery) {
        if (ObjectUtil.isNull(queryBindMachineBo.getUserId())) {
            queryBindMachineBo.setUserId(LoginHelper.getUserId());
        }
        IPage<SysUserMachineVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SysUserMachineVo> list = baseMapper.findBindMachine(page, queryBindMachineBo);
        return TableDataInfo.build(list);
    }

    @Override
    public SummaryTradingPointsVo summaryTradingPoints(SummaryTradingPointsBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        List<SysUserMachine> list = lambdaQuery().eq(SysUserMachine::getBindUserId, bo.getUserId()).list();
        if (CollUtil.isEmpty(list)) {
            return SummaryTradingPointsVo.builder()
                .tradingAmount(BigDecimal.ZERO)
                .transferPoints(BigDecimal.ZERO).build();
        } else {
            List<String> machineList = list.stream().map(SysUserMachine::getSn).toList();
            QueryTotalTransactionBySnsBo queryTotalTransactionBySnsBo = QueryTotalTransactionBySnsBo.builder()
                .sns(machineList)
                .startTime(bo.getStartTime())
                .endTime(bo.getEndTime()).build();
            //交易金额
            BigDecimal totalTransactionBySns = tradingRecordsMapper.queryTotalTransactionBySns(queryTotalTransactionBySnsBo);
            QueryTotalTransactionBySnsBo queryTotalByUser = QueryTotalTransactionBySnsBo.builder()
                .userId(bo.getUserId())
                .startTime(bo.getStartTime())
                .endTime(bo.getEndTime()).build();
            BigDecimal bigDecimal = creditCardRewardRecordsMapper.queryCashBackPointsByUser(queryTotalByUser);
            //转换金额
            return SummaryTradingPointsVo.builder()
                .tradingAmount(totalTransactionBySns)
                .transferPoints(bigDecimal)
                .build();
        }
    }


}
